package com.atguigu.springcloud.service.impl;

import com.atguigu.springcloud.service.CircuitService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;

/**
 * @author timiv
 */
@Service
public class CircuitServiceImpl implements CircuitService {


    /**
     * 调用10后如果失败率达到60%，所有的请求都进行降级处理，不在执行任何方法逻辑
     * 并且会在设定的时间窗口期随机的对部分请求方法逻辑处理，如果成功的概率增加则恢复对程序方法的调用
     * 否则继续对该方法执行降级处理
     * @param id
     * @return
     */
    @Override
    @HystrixCommand(fallbackMethod = "payment_circuit_fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启熔断
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后熔断
    })
    public String payment_circuit(Integer id) {
        if(id < 0){
            throw new RuntimeException("id不能为负数");
        }
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号："+ UUID.randomUUID().toString();
    }

    public String payment_circuit_fallback(Integer id){
        return "id不能为负数，请稍后再试，/(ㄒoㄒ)/~~ id:"+id;
    }
}
